import axios from 'axios'
import { useInfiniteQuery } from 'react-query'

async function fetchUser ({ pageParam = 1 }) {
  return axios.get(`https://reqres.in/api/users?page=${pageParam}`)
}

function LoadMore () {
  const {
    isLoading,
    isFetching,
    hasNextPage,
    fetchNextPage,
    data
  } = useInfiniteQuery('users', fetchUser, {
    getNextPageParam (current) {
      if (current.page < current.total_pages) {
        return current.page + 1
      }
    }
  })
  if (isLoading) return <div>loading...</div>
  return (
    <div>
      <ul>
        {data.pages.map(page =>
          page.data.map(user => <li key={user.id}>{user.first_name}</li>)
        )}
      </ul>
      {hasNextPage && <button onClick={() => fetchNextPage()}>加载更多</button>}
      {isFetching && <div>fetching...</div>}
    </div>
  )
}

export default LoadMore
